import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense
from keras.preprocessing.text import Tokenizer
from keras_preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report

# 从CSV文件中读取数据
data = pd.read_csv('data.csv')
data = data.sample(frac=1).reset_index(drop=True)

# 提取文本和标签列
text = data['review'].values
labels = data['label'].values
print(len(text))
print(len(labels))

# 创建标签编码器
label_encoder = LabelEncoder()

# 对标签进行编码
labels = label_encoder.fit_transform(labels)

# 对文本进行分词和编码
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(text)
sequences = tokenizer.texts_to_sequences(text)

# 对文本序列进行填充
max_len = max([len(seq) for seq in sequences])
sequences = pad_sequences(sequences, maxlen=max_len)

# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(sequences, labels, test_size=0.1 ,random_state=42)

# 定义模型结构
embedding_dim = 50
filters = 64
kernel_size = 5
hidden_dims = 128
num_classes = len(np.unique(labels))
print(num_classes)

model = Sequential()
model.add(Embedding(5000, embedding_dim, input_length=max_len))
model.add(Conv1D(filters, kernel_size, activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(hidden_dims, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 训练模型
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test))

# 评估模型
# y_pred = model.predict_classes(x_test)
y_pred = model.predict(x_test)
y_pred=np.argmax(y_pred,axis=1)
target_names = label_encoder.classes_
target_names = [str(cn) for cn in target_names]
print(classification_report(y_test, y_pred, target_names=target_names))

# 保存模型
model.save('emotion_model.h5')